<?php
// +----------------------------------------------------------------------
// | 七牛云
// +----------------------------------------------------------------------

namespace helper\storage\driver;

use helper\storage\Driver;
use Qiniu\Auth;
use Qiniu\Config;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

class Kodo implements Driver
{
    private $config;

    private $handler;

    public function __construct($config)
    {
        $this->config  = $config;
        $this->handler = new Auth($config['accessKey'], $config['secretKey']);
    }

    /**
     * 上传文件
     * @param string $object
     * @param string $filePath
     * @return array
     */
    public function putFile(string $object, string $filePath): array
    {
        $filePath = $filePath . '/' . $object;
        // 生成上传 Token
        $token = $this->handler->uploadToken($this->config['bucket']);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $object, $filePath);
        if ($err !== null) {
            return ['code' => 1, 'msg'=> $err];
        } else {
            return ['code' => 0, 'msg'=> '', 'data' => $ret];
        }
    }

    /**
     * 删除文件
     * @param string $object
     * @return array
     */
    public function deleteFile(string $object): array
    {
        $config = new Config();
        $bucketManager = new BucketManager($this->handler, $config);
        $err = $bucketManager->delete($this->config['bucket'], $object);
        if ($err) {
            return ['code' => 1, 'msg'=> $err];
        }
        return ['code' => 0, 'msg'=> ''];
    }
}